package com.sh.data.engine.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

/**
 * @author: zigui.zdf
 * @description:
 * @date: 2021/5/21 16:59
 */
public class JsonPathUtil {

    /**
     * 根据json获取jsonpath表达式，排除数组
     *
     * @param json
     * @return
     */
    public static List<String> getJsonPaths(String json) {
        List<String> jsonpaths = Lists.newArrayList();

        if (StringUtils.isBlank(json)) {
            return jsonpaths;
        }

        try {
            Object parse = JSON.parse(json);

            // 根
            jsonpaths.add("$");

            if (parse instanceof JSONObject) {
                JSONObject jsonObject = (JSONObject) parse;
                getJsonPaths(jsonObject, "$", jsonpaths);
            }

            jsonpaths.sort(
                (o1, o2) -> {
                    return o1.compareTo(o2);
                });

        } catch (Exception ignore) {

        }

        return jsonpaths;
    }

    private static void getJsonPaths(JSONObject jsonObject, String parentKey, List<String> keys) {
        jsonObject.forEach(
            (k, v) -> {
                String key = parentKey + "." + k;

                keys.add(key);

                if (null == v) {
                    return;
                }
                if (v instanceof JSONObject) {
                    JSONObject json = (JSONObject) v;
                    getJsonPaths(json, key, keys);
                }
            });
    }
}
